package com.chalk.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.chalk.common.util.RedisUtil;
import com.chalk.common.util.Result;
import com.chalk.service.AliSmsService;
import com.chalk.util.alisms.AliSmsConfig;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class AliSmsServiceImpl implements AliSmsService {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public Result sendSms(String phone, String openId) {
        /**
         * 老版本调用---->
         */
        /* 可自助调整超时时间 */
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            /* 初始化acsClient,暂不支持region化 */
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliSmsConfig.accessKeyId, AliSmsConfig.secret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", AliSmsConfig.domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            /* 组装请求对象-具体描述见控制台-文档部分内容 */
            SendSmsRequest request = new SendSmsRequest();
            /* 必填:待发送手机号 */
            request.setPhoneNumbers(phone);
            /* 必填:短信签名-可在短信控制台中找到 */
            request.setSignName(AliSmsConfig.signValue);
            /* 必填:短信模板-可在短信控制台中找到 */
            request.setTemplateCode(AliSmsConfig.templateValue);
            /* 可选:模板中的变量替换JSON串 */
            String code=RandomStringUtils.random(6,false,true);
            request.setTemplateParam("{\"code\":\"" + code + "\"}");
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            String responseCode = sendSmsResponse.getCode();
            if ("OK".equals(responseCode)) {
                redisUtil.set(openId+"phone",phone,300);//5分钟
                redisUtil.set(openId,code,300);//5分钟
                return Result.success("验证码发送成功！");
            } else {
                return Result.fail("验证码发送失败！");
            }
        } catch (ClientException e) {
            e.getErrMsg();
        }
        return Result.fail("系统异常！");
    }
}
